package homestatistics

import (
	// "net/http"

	// "time"
	// "github.com/dgrijalva/jwt-go"

	"encoding/json"
	"strconv"
	"oxy_server/model"
	"oxy_server/module/log"
	"oxy_server/res/cmsserver/designplan"
	"oxy_server/res/cmsserver/productplan"
	"oxy_server/until"

	"github.com/labstack/echo"
	"gopkg.in/mgo.v2/bson"
)

type (
	operationplan struct {
		ID             bson.ObjectId `json:"_id" bson:"_id"`
		BatchNumber    string        `json:"batchnumber" bson:"batchnumber"`       //批次号
		StyleNumber    string        `json:"stylenumber" bson:"stylenumber"`       //计划款数
		CategoryId     string        `json:"categoryid" bson:"categoryid"`         //产品大类
		ProductKind    string        `json:"productkind" bson:"productkind"`       //品类
		TargetCost     string        `json:"targetcost" bson:"targetcost"`         //目标成本
		TargetPrice    string        `json:"targetprice" bson:"targetprice"`       //目标售价
		PremiumRate    string        `json:"premiumrate" bson:"premiumrate"`       //加价倍率
		Brand          string        `json:"brand" bson:"brand"`                   //品牌
		TargetNumber   string        `json:"targetnumber" bson:"targetnumber"`     //计划款数
		DesignNumber   int           `json:"designnumber" bson:"designnumber"`     //设计组款数 判断条件 分配给品牌的算一款
		ProductNumber  int           `json:"productnumber" bson:"productnumber"`   //生产组款数 下过订单的算一款
		MeetingNumber  int           `json:"meetingnumber" bson:"meetingnumber"`   //过会组款数 过会的算一款
		Value          string        `json:"value" bson:"value"`                   //计划货值
		DesignValue    int           `json:"designvalue" bson:"designvalue"`       //设计组货值
		ProductValue   int           `json:"productvalue" bson:"productvalue"`     //生产组货值
		PlanDetails    []Detail      `json:"plandetails" bson:"plandetails"`       //运营计划详细
		DesignDetails  []Detail      `json:"designdetails" bson:"designdetails"`   //设计组详细
		ProductDetails []Detail      `json:"productdetails" bson:"productdetails"` //生产组详细
		MeetingDetails []Detail      `json:"meetingdetails" bson:"meetingdetails"` //过会组详细

	}
	Detail struct {
		Kind        string `json:"kind" bson:"kind"`               //品类
		Value       string `json:"value" bson:"value"`             //计划货值
		StyleNumber string `json:"stylenumber" bson:"stylenumber"` //计划款数
		ActualValue int    `json:"actualvalue" bson:"actualvalue"` //实际货值
		ActualCount int    `json:"actualcount" bson:"actualcount"` //实际款数
	}
)

type OXYHomeStatistics struct{}

func NewOXYHomeStatistics() *OXYHomeStatistics {
	operationPlanData := &OXYHomeStatistics{}
	return operationPlanData
}

func (ohs *OXYHomeStatistics) GetOperationPlanListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	sort := c.QueryParam("sort")
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "operation_plan"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	// 查询运营计划
	query, count, err := model.DB().QuerySort(M, currentpage, perpage, sort)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []operationplan{}
	psmerge := []operationplan{} /* 声明变量，默认 map 是 nil */
	var map_variable map[string]operationplan

	/* 使用 make 函数 */
	map_variable = make(map[string]operationplan)
	query.All(&ps)
	for _, item := range ps {
		key := item.BatchNumber + item.Brand
		captial, ok := map_variable[key]
		if ok {
			// 累加计划款数
			totalCount, _ := strconv.Atoi(captial.StyleNumber)
			currCount, _ := strconv.Atoi(item.StyleNumber)
			s := strconv.Itoa(currCount + totalCount)
			// 累加计划货值
			totalValue, _ := strconv.ParseFloat(captial.Value, 64)
			currValue, _ := strconv.ParseFloat(item.Value, 64)
			v := strconv.FormatFloat(totalValue+currValue, 'E', -1, 64)
			captial.StyleNumber = s
			captial.Value = v
			captial.PlanDetails = append(captial.PlanDetails, Detail{
				Kind:        item.ProductKind,
				Value:       item.Value,
				StyleNumber: item.StyleNumber,
			})

			map_variable[key] = captial
		} else {
			item.PlanDetails = append(item.PlanDetails, Detail{
				Kind:        item.ProductKind,
				Value:       item.Value,
				StyleNumber: item.StyleNumber,
			})
			map_variable[key] = item
		}
	}

	for index, _ := range map_variable {
		psmerge = append(psmerge, map_variable[index])
	}
	var batchNumberList []interface{}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "design_plan"
	for _, item := range ps {
		var queryMap map[string]string /*创建集合 */
		queryMap = make(map[string]string)
		queryMap["batch"] = item.BatchNumber
		batchNumberList = append(batchNumberList, queryMap)
	}
	// 根据运营计划 查询所有数据当前运营计划的设计组数据
	querydes, _, errs := model.DB().Query(bson.M{"$or": batchNumberList}, 0, 0)
	if errs != nil {
		log.Error("按批次号查询设计组失败", errs)
		c.JSON(200, map[string]interface{}{
			"msg":   "success",
			"data":  "[]",
			"count": 0,
		})
		return errs
	}
	designnList := []designplan.Designplan{}
	querydes.All(&designnList)

	// 遍历运营计划
	for index, item := range psmerge {
		psmerge[index].DesignNumber = 0
		psmerge[index].DesignDetails = []Detail{}
		// 遍历所有设计组数据
		for _, des := range designnList {
			// 当批次号等于设计组批次号
			if item.BatchNumber == des.Batch {
				price, _ := strconv.Atoi(des.FactoryCost)
				for _, order := range des.Order {
					// 当运营计划中品牌等于分配中的品牌
					if order.Brand == psmerge[index].Brand {
						psmerge[index].DesignNumber++
						count, _ := strconv.Atoi(order.Count)
						psmerge[index].DesignValue += price * count

						psmerge[index].DesignDetails = append(psmerge[index].DesignDetails, Detail{
							Kind:        des.ProductKind,
							Value:       strconv.Itoa(price * count),
							StyleNumber: "1",
						})

					}
				}

			}
		}
	}

	model.DB().Dbname = "OxyCms"
	model.DB().Document = "product_plan"

	// 根据运营计划 查询所有数据当前运营计划的生产组数据
	querypro, _, errs := model.DB().Query(bson.M{"$or": batchNumberList, "brand": psmerge[0].Brand}, 0, 0)
	if errs != nil {
		log.Error("按批次号和品牌查询生产组组失败", errs)
		c.JSON(200, map[string]interface{}{
			"msg":   "success",
			"data":  psmerge,
			"count": count,
		})
	}
	productList := []productplan.Productplan{}
	querypro.All(&productList)

	// 遍历运营计划
	for index, item := range psmerge {
		psmerge[index].ProductNumber = 0
		psmerge[index].MeetingNumber = 0
		psmerge[index].ProductDetails = []Detail{}
		psmerge[index].MeetingDetails = []Detail{}
		// 遍历所有生产组数据
		for _, pro := range productList {
			// 当批次号等于设计组批次号
			if item.BatchNumber == pro.Batch {
				price, _ := strconv.Atoi(pro.FinallyCost)
				if pro.OrderStatus == 1 {
					psmerge[index].ProductNumber++
					psmerge[index].ProductValue += price * pro.OrderCount
					psmerge[index].ProductDetails = append(psmerge[index].ProductDetails, Detail{
						Kind:        pro.ProductKind,
						Value:       strconv.Itoa(price * pro.OrderCount),
						StyleNumber: "1",
					})
				}
				if pro.MeetingStatus == 1 {
					psmerge[index].MeetingNumber++
					psmerge[index].MeetingDetails = append(psmerge[index].ProductDetails, Detail{
						Kind:        pro.ProductKind,
						StyleNumber: "1",
					})
				}

			}
		}
	}

	if err != nil {
		log.Error("json 转string error", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  psmerge,
		"count": count,
	})

	return nil
}

func (ohs *OXYHomeStatistics) GetDesignPlanListHandler(c echo.Context) error {
	currentpage, err := strconv.Atoi(c.QueryParam("currentpage"))
	perpage, err := strconv.Atoi(c.QueryParam("perpage"))
	sort := c.QueryParam("sort")
	jsonquery := c.QueryParam("like")
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	model.DB().Dbname = "OxyCms"
	model.DB().Document = "operation_plan"
	M, err := until.JsonToBson(jsonquery)
	if err != nil {
		log.Error("json-> bson 失败", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	query, _, err := model.DB().QuerySort(M, currentpage, perpage, sort)
	if err != nil {
		log.Error("查询出错", err)
		c.JSON(404, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	ps := []operationplan{}
	query.All(&ps)
	desList := []designplan.Designplan{}
	for index, item := range ps {
		model.DB().Dbname = "OxyCms"
		model.DB().Document = "design_plan"
		querydes, _, errs := model.DB().Query(bson.M{"batch": item.ID.Hex()}, 0, 0)
		List := []designplan.Designplan{}

		querydes.All(&List)

		if errs != nil {
			ps[index].DesignNumber = 0
		} else {
			for _, item := range List {
				desList = append(desList, item)
			}
		}
	}
	str, err := json.Marshal(desList)
	if err != nil {
		log.Error("解析参数错误", err)
		c.JSON(403, map[string]interface{}{
			"msg": "error",
		})
		return err
	}
	c.JSON(200, map[string]interface{}{
		"msg":   "success",
		"data":  string(str),
		"count": len(desList),
	})

	return nil
}
